﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    //this page allows the administrater to add a new product to database
    public partial class NewProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // If the page was returned from another page, 
                // fill the data in the controls
                if (Request.QueryString["Parameters"] != null)
                {
                    string[] parameters = Request.QueryString["Parameters"].Split(',');

                    nameTxtbox.Text = parameters[0].Split('=')[1];
                    priceTxtbox.Text = parameters[1].Split('=')[1];
                    txtItemsInStock.Text = parameters[2].Split('=')[1];
                    txtThreshold.Text = parameters[3].Split('=')[1];
                    chkNotifyBelowThreshold.Checked =
                        Boolean.Parse(parameters[4].Split('=')[1]);
                    txtMaxDaysFromLastOrder.Text = parameters[5].Split('=')[1];
                    chkNotifyDeadStock.Checked =
                        Boolean.Parse(parameters[6].Split('=')[1]);
                }
            }
        }

        //function for redirecting the admin back to his homepage without adding a new product.
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        //function checks if the string contains a number and only a number.
        public bool Check(string str)
        {
            double Num;
            bool isNum = (double.TryParse(str, out Num));
            return isNum;
        }

        //activated when the ok button is pressed
        protected void okBtn_Click(object sender, EventArgs e)
        {
            Queries queries = new Queries();

            //making sure all text boxes have been filled
            if (nameTxtbox.Text == "" || priceTxtbox.Text == "" || Check(priceTxtbox.Text) == false)
            {
                //if something is missing- print apropriot message to screan.
                empty.Text = ".קלט לא תקין";
            }
            else
            {   //making sure the new client does not exist in our data base.
                if (queries.ProductExists(nameTxtbox.Text) == false)
                {
                    // Disable the buttons so the user can't interfere
                    backBtn.Enabled = false;
                    okBtn.Enabled = false;

                    // If the field items in stock or threshold wasn't changed or is not numeric, save it as 0
                    int itemsInStock = 0;
                    Int32.TryParse(txtItemsInStock.Text, out itemsInStock);
                    int threshold = 0;
                    Int32.TryParse(txtThreshold.Text, out threshold);

                    int maxDaysFromLastOrder = 365;
                    Int32.TryParse(txtMaxDaysFromLastOrder.Text, out maxDaysFromLastOrder);

                    //adding the new client into our database
                    queries.AddProduct(nameTxtbox.Text, Double.Parse(priceTxtbox.Text),
                        Int32.Parse(categoryCombo.SelectedItem.Value), itemsInStock,
                        threshold, chkNotifyBelowThreshold.Checked, maxDaysFromLastOrder,
                        chkNotifyDeadStock.Checked);

                    // Announce success and wait for 2 seconds before redirecting
                    empty.Text = "המוצר נוסף בהצלחה";
                    redirectionTimer.Enabled = true;
                }
                //if the client already exists- print apropriate message to screan
                else
                {
                    empty.Text = "שם המוצר כבר נמצא במערכת";
                }
            }
        }

        /// <summary>
        /// Add new category
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkAddCategory_Click(object sender, EventArgs e)
        {
            // Save the values that the user entered
            String parameters = "Parameters=" + "Name=" + nameTxtbox.Text + ",Price=" + priceTxtbox.Text +
                ",ItemsInStock=" + txtItemsInStock.Text + ",Threshold=" + txtThreshold.Text +
                ",NotifyLack=" + chkNotifyBelowThreshold.Checked + ",MaxDays=" +
                txtMaxDaysFromLastOrder.Text + ",NotifyDeadStock=" +
                chkNotifyDeadStock.Checked;

            Response.Redirect("~/Admin/NewCategory.aspx?ReturnUrl=NewProduct.aspx?" +
                parameters);
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }
    }
}